package cn.zebra.dev.shop.module.delivery.service.impl;

import cn.zebra.dev.common.utils.DateUtils;
import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import cn.zebra.dev.shop.module.delivery.dao.DeliveryDao;
import cn.zebra.dev.shop.module.delivery.entity.DeliveryEntity;
import cn.zebra.dev.shop.module.delivery.entity.DeliveryItemEntity;
import cn.zebra.dev.shop.module.delivery.service.DeliveryItemService;
import cn.zebra.dev.shop.module.delivery.service.DeliveryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 运费模板(主表)
 *
 * @author runnable
 */
@Service
public class DeliveryServiceImpl extends ServiceImpl<DeliveryDao, DeliveryEntity> implements DeliveryService {

    @Autowired
    private DeliveryItemService itemService;

    @Override
    public PageUtils<DeliveryEntity> findPage(Map<String, Object> params) {
        QueryWrapper<DeliveryEntity> wrapper = new QueryWrapper<>();
        IPage<DeliveryEntity> page = this.page(
                new Query<DeliveryEntity>(params).getPage(),
                wrapper
        );
        return new PageUtils<>(page);
    }

    /**
     * 保存运费模板
     *
     * @param entity   运费模板
     * @param createId 创建人id
     * @return 保存成功返回True 保存失败失败返回False
     */
    @Override
    public boolean saveDelivery(DeliveryEntity entity, Long createId) {
        if (entity.getShopId() == null) {
            entity.setShopId(0L);
        }
        entity.setDeleteFlag(false);
        entity.setCreateId(createId);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateId(0L);
        entity.setUpdateTime(DateUtils.defaultTime());
        if (!this.save(entity)) {
            return false;
        }
        Long deliveryId = entity.getId();
        List<DeliveryItemEntity> itemList = entity.getItemList();
        Set<Long> cityIds = new HashSet<>();
        for (int i = itemList.size() - 1; i >= 0; i--) {
            DeliveryItemEntity itemEntity = itemList.get(i);
            if (!cityIds.addAll(itemEntity.getCityIds())) {
                return false;
            }
            itemEntity.setDeliveryId(deliveryId);
        }
        return itemService.saveBatch(itemList);
    }

    /**
     * 保存运费模板
     *
     * @param id       被修改运费模板的id
     * @param entity   运费模板
     * @param updateId 修改人id
     * @return 保存成功返回True 保存失败失败返回False
     */
    @Override
    public boolean updateDelivery(Long id, DeliveryEntity entity, Long updateId) {
        entity.setDeleteFlag(false);
        entity.setCreateId(null);
        entity.setCreateTime(null);
        entity.setUpdateId(updateId);
        LocalDateTime now = LocalDateTime.now();
        entity.setUpdateTime(now);
        if (!this.update(entity, "id = {0}", id)) {
            return false;
        }
        List<DeliveryItemEntity> sourceItemList = itemService.findListByFieldValue(DeliveryItemEntity::getDeliveryId, id);
        Long deliveryId = entity.getId();
        List<DeliveryItemEntity> itemList = entity.getItemList();
        Set<Long> cityIds = new HashSet<>();
        List<DeliveryItemEntity> saveList = new ArrayList<>();
        List<DeliveryItemEntity> updateList = new ArrayList<>();
        for (int i = itemList.size() - 1; i >= 0; i--) {
            DeliveryItemEntity itemEntity = itemList.get(i);
            if (!cityIds.addAll(itemEntity.getCityIds())) {
                return false;
            }
            itemEntity.setDeliveryId(deliveryId);
            Long itemEntityId = itemEntity.getId();
            if (itemEntityId != null) {
                //如果删除失败说明伪造id传递
                if (!sourceItemList.removeIf(source -> source.getId().equals(itemEntityId))) {
                    return false;
                }
                updateList.add(itemEntity);
            } else {
                saveList.add(itemEntity);
            }
        }
        if (updateList.size() > 0 && !itemService.updateBatch(updateList)) {
            return false;
        }
        if (saveList.size() > 0 && !itemService.saveBatch(saveList)) {
            return false;
        }
        //删除旧商品规格
        if (!CollectionUtils.isEmpty(sourceItemList)) {
            List<Long> itemIds = sourceItemList.stream().map(DeliveryItemEntity::getId).collect(Collectors.toList());
            return itemService.removeByIds(itemIds);
        }
        return true;
    }

    @Override
    public DeliveryEntity findById(Long id) {
        DeliveryEntity entity = super.findById(id);
        entity.setItemList(itemService.findListByFieldValue(DeliveryItemEntity::getDeliveryId, id));
        return entity;
    }
}
